<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Page;
use App\Teacher;
use App\Publish;
use App\Assessor;
use App\Parents;
use App\Student;
use App\Student_parent;
use App\Organization;
use App\Flag;
use App\Teacher_organize;
use DB;
use Config;

class TeacherController extends Controller
{
  /**
   * 获取教师列表.
   *
   * @return Response
   */
  public function getTeacher(Request $request)
  {
    // 学年
    $schoolYear = $request->input('schoolYear', 0);
    if(!$schoolYear){
      // 根据年月份获取当前学年
      // 获取当前年份、月份
      $currentYear = date('Y');
      $currentMonth = date('m');
      if($currentMonth<8){
        $schoolYear = $currentYear - 1;
      }else{
        $schoolYear = $currentYear;
      }
    }

    /*$teacherInfos = Teacher_organize::whereRaw("organizeID in (select ID from organize where schoolYear=$schoolYear) or organizeID=0")->get()->toArray();
    $teacher_classes = array();
    foreach ($teacherInfos as $teacherInfo) {
      $teacherID = $teacherInfo["teacherID"];

      $organizeID = $teacherInfo["organizeID"];
      $type = $teacherInfo["type"];
      $projectIDs = $teacherInfo["projectIDs"];

      $teacher_classes[$teacherID][] = array("organizeID" => $organizeID, "type" => $type, "projectIDs" => $projectIDs);
    }

    $teachers = array();
    foreach ($teacher_classes as $teacherID => $classes) {
      $teacherInfo = Teacher::find($teacherID);
      if(!$teacherInfo["state"]){
        $teacherInfo["classes"] = $classes;

        $teachers[] = $teacherInfo;
      }
    }*/

    //
    $teachers = Teacher::where('state', 0)->where('schoolYear', $schoolYear)->get();

    return Reply($teachers, 200);
  }

  /**
   * 获取单个教师信息.
   * 
   * @return Response
   */
  public function getsingleTeacher(Request $request, $id){
    /*// 学年
    $schoolYear = $request->input('schoolYear', 0);
    if(!$schoolYear){
      // 根据年月份获取当前学年
      // 获取当前年份、月份
      $currentYear = date('Y');
      $currentMonth = date('m');
      if($currentMonth<8){
        $schoolYear = $currentYear - 1;
      }else{
        $schoolYear = $currentYear;
      }
    }*/

    // 教师信息
    $teacher = Teacher::find($id);
    if(count($teacher)<1){
      return Reply(array("message" => "错误的ID：暂无信息"), 400);
    }

    /*$teacherInfos = Teacher_organize::whereRaw("teacherID=$id and organizeID in (select ID from organize where schoolYear=$schoolYear) or organizeID=0")->get()->toArray();
    $teacher_classes = array();
    foreach ($teacherInfos as $teacherInfo) {
      $organizeID = $teacherInfo["organizeID"];
      $type = $teacherInfo["type"];
      $projectIDs = $teacherInfo["projectIDs"];

      $teacher_classes[] = array("organizeID" => $organizeID, "type" => $type, "projectIDs" => $projectIDs);
    }

    $teascher["classes"] = $teacher_classes;*/

    return Reply($teacher, 200);
  }

  /**
   * 绑定教师.
   * 
   * @return Response
   */
  public function teacherbind(Request $request)
  {
    // 用户openID
    $openID = $request->input('openID');
    if(!$openID){
      return Reply(array("message" => "请授权登陆"), 400);
    }

    // 姓名
    $name = $request->input('name');
    if(!$name){
      return Reply(array("message" => "姓名是必要字段"), 400);
    }

    // 手机
    $mobile = $request->input('phone');
    if(!$mobile){
      return Reply(array("message" => "手机是必要字段"), 400);
    }
    if(!is_mobile($mobile))
    {
      return Reply(array("message" => "请输入正确手机号码"), 400);
    }

    // emis账户信息
    $login = $request->input('login', 0);

    // 班级/年级
    $organize = $request->input('classes');

    // 
    $status = $request->input('status', 1);

    // 学年
    $schoolYear = $request->input('schoolYear', 0);
    if(!$schoolYear){
      // 根据年月份获取当前学年
      // 获取当前年份、月份
      $currentYear = date('Y');
      $currentMonth = date('m');
      if($currentMonth<8){
        $schoolYear = $currentYear - 1;
      }else{
        $schoolYear = $currentYear;
      }
    }

    // 判断教师是否存在
    $exist = Teacher::where('openID', $openID)->where('schoolYear', $schoolYear)->get()->toArray();
    if($exist){
      // 存在则更新
      $type = "update";
    }else{
      // 不存在则新增
      $type = "create";
    }

    // 开始事务
    DB::beginTransaction();

    switch ($type) {
      case 'update':
        // 更新
        Teacher::where('openID', $openID)->where('schoolYear', $schoolYear)->update(array(
          "status" => $status,
          "state" => 0,
          "name" => $name,
          "phone" => $mobile,
          "classes" => $organize,
          "login" => $login,
          "schoolYear" => $schoolYear
        ));

        $bindID = Teacher::where('openID', $openID)->where('schoolYear', $schoolYear)->value('id');
        break;
      
      case 'create':
        // 保存（新增）
        $teacher = new Teacher;

        $teacher->openID = $openID;
        $teacher->name = $name;
        $teacher->phone = $mobile;
        $teacher->classes = $organize;
        $teacher->login = $login;
        $teacher->schoolYear = $schoolYear;

        $result = $teacher->save();
        if(!$result){
          DB::rollBack();

          return Reply(array("message" => "服务器错误，绑定失败，请稍后重试"), 400);
        }

        // 获取ID
        $bindID = $teacher->id;
        break;

      default:
      return Reply(array("message" => "error status"), 400);
    }

    // 记录教师——班级关系
    $organizes = json_decode($organize, true);
    foreach ($organizes as $organize) {
      $organizeID = $organize["organizeID"];
      $type = $organize["type"];
      // $projectIDs = $organize["projectIDs"];

      if($organizeID){
        // 判断是否已存在
        $t_organize = Teacher_organize::where('teacherID', $bindID)->where('organizeID', $organizeID)->get()->toArray();
        if($t_organize){
          // 存在，更新记录
          Teacher_organize::where('teacherID', $bindID)->where('organizeID', $organizeID)->update(array("type" => $type));
        }else{
          // 不存在，新建
          $teacher_organize = new Teacher_organize;

          $teacher_organize->organizeID = $organizeID;
          $teacher_organize->teacherID = $bindID;
          $teacher_organize->type = $type;
          // $teacher_organize->projectIDs = json_encode($projectIDs);

          $result = $teacher_organize->save();
          if(!$result){
            DB::rollBack();

            return Reply(array("message" => "服务器错误，保存教师班级关系失败，请稍后重试"), 400);
          }
        }
      }
    }

    DB::commit();

    return Reply(array("ID" => $bindID), 200);
  }

  /**
   * 教师取消绑定.
   *
   * @return Response
   */
  public function unbound(Request $request)
  {
    // 
    $teacherID = $request->input('teacherID');
    if(!$teacherID){
      return Reply(array("message" => "ID是必要字段"), 400);
    }

    Teacher::where('id', $teacherID)->update(array("status" => 1, "state" => 1));

    // 删除教师所有消息，messages，message_buffer，message_confirm，message_organize，

    return Reply(array("message" => "取消绑定成功"), 200);
  }

  /**
   * 判断教师是否已经绑定.
   * 
   * @return Response
   */
  public function isbind(Request $request){
    // 用户openID
    $openID = $request->input('openID');

    // 学年
    $schoolYear = $request->input('schoolYear', 0);
    if(!$schoolYear){
      // 根据年月份获取当前学年
      // 获取当前年份、月份
      $currentYear = date('Y');
      $currentMonth = date('m');
      if($currentMonth<8){
        $schoolYear = $currentYear - 1;
      }else{
        $schoolYear = $currentYear;
      }
    }

    $teacher = Teacher::where('openID', $openID)->where('schoolYear', $schoolYear)->get()->toArray();
    if($teacher){
      $ID = $teacher[0]["id"];
      $name = $teacher[0]["name"];
      $status = $teacher[0]["status"];
      $state = $teacher[0]["state"];

      $bindStatus = true;

      if(!$status){
        $verifyStatus = true;
      }else{
        $verifyStatus = false;
      }

      if(!$state){
        $deleteStatus = false; // 未删除
      }else{
        $deleteStatus = true; // 已删除
      }
    }else{
      $ID = "";
      $bindStatus = false;
      $verifyStatus = false;
      $deleteStatus = false;
      return Reply(array( "bindState" => $bindStatus, "verifyState" => $verifyStatus, "deleteState" => $deleteStatus), 200);
    }

    return Reply(array('name' =>$name,"ID" => $ID, "bindState" => $bindStatus, "verifyState" => $verifyStatus, "deleteState" => $deleteStatus), 200);
  }

  /**
   * 获取教师发布的内容.
   * 1 3 4 5 6 11 13 
   * @return Response
   */
  public function getpage($teacherID)
  {
    // 获取内容列表
    $shows = Page::where('remove', '0')->where('teacherID', $teacherID)->orderby('ID', 'DESC')->get();
    $exhibition = array();
    if(count($shows)>0){
      foreach ($shows as $show) {
        $pageID = $show["ID"];
        $organizeIDs = Publish::where("pageID", $pageID)->pluck("organizeID")->toArray();
        // $organizeIDs = json_decode($organizeIDs);
        $organizes = array();
        if(count($organizeIDs)>0){
          $organizeIDs = array_unique($organizeIDs);
          foreach ($organizeIDs as $organizeID) {
            if($organizeID==0){
              $name = "全校";
              $content = null;
            }else{
              $organize = Organization::find($organizeID);

              $name = $organize["name"];
              $parent = $organize["parent"];
              if(!$parent){
                $name = $name."年级";
              }
              $content = $organize["content"];
            }

            $organizes[] = array("ID" => $organizeID, "name" => $name, "content" => $content);
          }
        }
        $show["organizes"] = $organizes;

        $subpage = $show["subpage"];
        $subpage = json_decode($subpage);

        $show["subpage"] = $subpage;

        $exhibition[] = $show;
      }
    }

    $deletes = Page::where('remove', '1')->where('teacherID', $teacherID)->orderby('ID', 'DESC')->get();
    $remove = array();
    if(count($deletes)>0){
      foreach ($deletes as $delete) {
        $subpage = $delete["subpage"];
        $subpage = json_decode($subpage);

        $delete["subpage"] = $subpage;

        $remove[] = $delete;
      }
    }

    return Reply(array("deleted" => $remove, "show" => $exhibition), 200);
  }

  /**
   * 获取教师下属班级及其信息.
   * 
   * @return Response
   */
  public function getTeacherClass(Request $request, $id){
    // 日期
    $evaluateDate = $request->input('date');
    if(!$evaluateDate){
      return Reply(array("message" => "请选择日期"), 400);
    }

    // 学年
    $schoolYear = $request->input('schoolYear', 0);
    if(!$schoolYear){
      // 根据年月份获取当前学年
      // 获取当前年份、月份
      $currentYear = date('Y');
      $currentMonth = date('m');
      if($currentMonth<8){
        $schoolYear = $currentYear - 1;
      }else{
        $schoolYear = $currentYear;
      }
    }

    // 日期转换成时间戳
    $date_str = date('Y-m-d', strtotime($evaluateDate));
    $arr = explode("-", $date_str);
    $year = $arr[0];
    $month = sprintf('%02d', $arr[1]);
    $day = sprintf('%02d', $arr[2]);
    $hour = $minute = $second = 0;
    $strap = mktime($hour, $minute, $second, $month, $day, $year);
    // 获取该天数字型星期几
    $week = getweek($evaluateDate);
    // 当前日期所在周上周日
    $startstamp = strtotime('-'.$week.' day', $strap);
    $startdate = date('Y-m-d', $startstamp);

    // 获取教师班级信息
    $teacher = Teacher::find($id);
    if(count($teacher)<1){
      return Reply(array("message" => "错误的ID：暂无信息"), 400);
    }

    /*$teacherInfos = Teacher_organize::whereRaw("teacherID=$id and organizeID in (select ID from organize where schoolYear=$schoolYear) or organizeID=0")->get()->toArray();
    $classes = array();
    foreach ($teacherInfos as $teacherInfo) {
      $organizeID = $teacherInfo["organizeID"];
      $type = $teacherInfo["type"];
      $projectIDs = $teacherInfo["projectIDs"];

      $classes[] = array("organizeID" => $organizeID, "type" => $type, "projectIDs" => $projectIDs);
    }*/

    $classes = $teacher->classes;
    $results = array();
    if($classes){
      $classes = json_decode($classes, true);
      $organizeIDs = array();
      foreach ($classes as $class) {
        // 班主任权限
        $type = $class["type"];
        if($type=="headmaster"){
          $organizeIDs[] = $class["organizeID"];
        }
      }
      $classes = implode(",", $organizeIDs);

      $organizations = array();
      if(in_array("0", $organizeIDs)){
        // 拥有查看全校的权限,获取所有班级
        $organizations = Organization::where('schoolYear', $schoolYear)->orderby('parent', 'ASC')->get()->toArray();
      }else{
        if($classes){
          $organizations = Organization::whereRaw("ID in ($classes) OR parent in ($classes) OR ID in (select parent from organize where ID in ($classes))")->orderby('parent', 'ASC')->get()->toArray();      
        }
      }

      if(count($organizations)<1){
        return Reply(array(), 200);
      }

      $gradeMap = array();
      foreach ($organizations as $pos => &$organization) {
        if($organization["parent"] == 0)
        {
          $gradeMap[$organization["ID"]] = &$organization;
          $organization["classes"] = array();
          $organization["name"] = $organization["name"].$organization["type"];

          unset($organization["ID"], $organization["type"], $organization["parent"], $organization["lockcontent"], $organization["totalScore"]);
          $results[] = &$organization;
          continue;
        }

        $grade = &$gradeMap[$organization["parent"]];
        unset($organization["type"], $organization["parent"], $organization["lockcontent"], $organization["totalScore"]);
        $grade["classes"][] = $organization;
      }

      $gradeArray = array("一" => "1", "二" => "2", "三" => "3","四" => "4", "五" => "5", "六" => "6","七" => "7", "八" => "8", "九" => "9");
      $gradeNos = array();
      foreach ($results as $key => &$result) {
        $classes = &$result["classes"];
        $gradeNo = mb_substr($result["name"], 0, 1, 'utf-8');
        $gradeNo = $gradeArray[$gradeNo];
        $classNos = array();
        foreach ($classes as &$class) {
          $classNo = mb_substr($class["name"], 2, 1, 'utf-8');
          $classNo = $gradeNo.$classNo;

          $classNos[] = $classNo;
          $class["classNo"] = $classNo;

          // 获取班级本周积分
          $weekRewds = DB::select("select score, reward, evaluateTime from evaluation where organizationID=" .$class["ID"]. " and evaluateDate>'".$startdate."' and evaluateDate<='".$evaluateDate."' order by evaluateDate ASC");

          $weekreward = 0;
          $score = 0;
          if($weekRewds){
            foreach ($weekRewds as $weekRewd) {
              $weekreward += $weekRewd->reward;

              $score = $weekRewd->score;
            }
          }
          // 获取最近一次评价总分
          // $evaluation = Evaluation::where('organizationID', $class["ID"])->orderby('evaluateDate', 'DESC')->first();
          // $score = $evaluation[0]["score"];

          // 上周流动红旗
          $weekFlag = Flag::where('organizationID', $class["ID"])->where('date', $startdate)->value("redFlag");
          if(!$weekFlag){
            $weekFlag = 0;
          }

          $class["weekreward"] = $weekreward;
          $class["weekFlag"] = $weekFlag;
          $class["score"] = $score;
        }
        array_multisort($classNos, SORT_ASC, $classes);
        $result["gradeNo"] = $gradeNo;
        $gradeNos[] = $gradeNo;
      }
      array_multisort($gradeNos, SORT_ASC, $results);
    }

    return Reply($results, 200);
  }

  // 获取登录教师个人信息
  public function getTeacherName(Request $request){
    // 用户openID
    $openID = $request->input('openID');
    $name = Teacher::where('openID', $openID)->get();
    $schoolName = config('app.EMIS_SCHOOLNAME');
    $name[0]['schoolName'] = $schoolName;
    return Reply($name, 200);
  }
  

  // 验证教师权限
  public function loginTeacher(Request $request){
    // 学年
    $schoolYear = $request->input('schoolYear', 0);
    if(!$schoolYear){
      // 根据年月份获取当前学年
      // 获取当前年份、月份
      $currentYear = date('Y');
      $currentMonth = date('m');
      if($currentMonth<8){
        $schoolYear = $currentYear - 1;
      }else{
        $schoolYear = $currentYear;
      }
    }

    // 用户openID
    $openID = $request->input('openID');
    // 根据openID判断是否绑定教师
    $teacher = Teacher::where('openID', $openID)->where('schoolYear', $schoolYear)->get()->toArray();
    // 是否绑定教师
    $state = false;
    // 是否班主任
    $type = false;
    // 是否具有全校权限
    $isAdmin = false;

    if($teacher){
      $status = $teacher[0]["status"];
      if(!$status){
        $state = true;

        $classes = $teacher[0]["classes"];
        $classes = json_decode($classes, true);
        if($classes){
          foreach ($classes as $value) {
            if(isset($value["type"])){
              $teachertype = $value["type"];
              if($teachertype=="headmaster"){
                $type = true;
              }
            }

            if(isset($value["organizeID"])){
              if($value["organizeID"]==0){
                $isAdmin = true;
              }
            }
          }
        }
      }
    }

     // 根据openID判断是否绑定考评员
    $status = Assessor::where('openID', $openID)->where('schoolYear', $schoolYear)->value("status");
    if($status==0){
      $assessorState = true;
    }else{
      $assessorState = false;
    }

    // 根据openID判断是否绑定家长
    $parentInfo = Parents::where('openID', $openID)->first();
    $status = $parentInfo["status"];
    $parentID = $parentInfo["id"];
    if($status==0){
      $isParent = true;
    }else{
      $isParent = false;
    }

     // 获取家长绑定孩子所在的班级
    $organizes = array();
    if($parentID && ($parentInfo["status"]==0)){
      $children = Student_parent::whereRaw("parentID=$parentID and status=0")->pluck("studentID")->toArray();
      if($children){
        $childIDs = implode(",", $children);

        // 获取孩子所属班级ID
        $organizeIDs = Student::whereRaw("id in ($childIDs)")->pluck("organizeID")->toArray();
        // 获取本学年的班级ID
        $organizeIDs = implode(",", $organizeIDs);
        $organizeIDs = Organization::whereRaw("ID in ($organizeIDs) and schoolYear=$schoolYear")->pluck("ID")->toArray();
        // 去重
        $organizeIDs = array_unique($organizeIDs);

        $organizes = array();
        foreach ($organizeIDs as $organizeID) {
          // 获取班级信息
          $organizeInfo = Organization::find($organizeID);
          if(!$organizeInfo){
            return Reply(array("message" => "ID为" . $organizeID . "的班级不存在，请检查数据是否正确"), 400);
          }

          $className = $organizeInfo["name"];

          $organizes[] = array("ID" => $organizeID, "name" => $className);
        }
      }
    }

    return Reply(array("isAdmin" => $isAdmin, "state" => $state, "isHeadmaster" => $type, "assessorState" => $assessorState, "isParent" => $isParent, "organizes" => $organizes, "openID" => $openID),200);
  }

}
